<template>
  <n-input-group style="">
    <n-select v-model:value="searchValAdministration" filterable placeholder="搜索行政区域" :options="AdministrationOptions"
      :loading="AdministrationSearchLoading" clearable remote @search="handleAdministrationSearchDebounce" />
    <n-button type="primary" @click="emits('searchclick', selItem);">搜索</n-button>
  </n-input-group>
</template>
<script setup lang=''>
import { onMounted, ref, onUnmounted, watch } from 'vue'
import { apiList } from '@/api/apiList'
import _ from 'lodash'


const emits = defineEmits([
    'searchclick',
])

const selItem = ref(null)

const searchValAdministration = ref(null)
const AdministrationSearchLoading = ref(false)
const AdministrationOptions = ref([])

watch(searchValAdministration, function (n, o) {
  viewer.entities.removeAll()
  if (n == null) {
    AdministrationOptions.value = []
    selItem.value = null
  } else {
    //添加行政区域到地图
    let item = NominatimRes[n]
    selItem.value = item

    let res_entities = []

    if (item.geojson.type == 'MultiPolygon') {
      item.geojson.coordinates.map((item1,index) => {
        item1.map(item2 => {
          let positions = Cesium.Cartesian3.fromDegreesArray(item2.flat(Infinity))
          res_entities.push(addPolygon(positions))
        })
      })
    }
    
    if (item.geojson.type == 'Polygon') {
      let positions = Cesium.Cartesian3.fromDegreesArray(item.geojson.coordinates.flat(Infinity))
      res_entities.push(addPolygon(positions))
    }
    viewer.flyTo(res_entities, {duration: 0.5})
  }
})

function addPolygon(positions){
  let e = viewer.entities.add({
    description: '', //描述
    show: true,
    polyline: {
      positions: positions,
      width: 3,
      material: Cesium.Color.BLUE.withAlpha(0.5),
    },
  })
  return e
}

let NominatimRes = []
const handleAdministrationSearch =  (query) => {
  searchValAdministration.value = null;
  AdministrationOptions.value = [];
  AdministrationSearchLoading.value = true
  apiList.getNominatimSearch({ format: 'jsonv2', polygon_geojson: 1, q: query }).then(res => {
    AdministrationSearchLoading.value = false
    if (!query.length) {
      AdministrationOptions.value = []
      return
    }
    AdministrationOptions.value = []
    NominatimRes = res
    res.map((item, index) => {
      if (item.category == 'boundary') {
        AdministrationOptions.value.push({
          label: item.display_name,
          value: index
        })
      }
    })
  })
}

const handleAdministrationSearchDebounce = _.debounce(handleAdministrationSearch,300)

</script>
<style lang='scss' scoped></style>